package com.renfei.multimediatask.ui.task2;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.renfei.multimediatask.R;
import com.renfei.multimediatask.base.BaseActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PlayPcmDataActivity extends BaseActivity {


    @BindView(R.id.tv_record_prompt)
    TextView tvRecordPrompt;
    @BindView(R.id.startRecord)
    Button startRecord;
    @BindView(R.id.stopRecord)
    Button stopRecord;
    @BindView(R.id.ll_btn_layout)
    RelativeLayout llBtnLayout;

    private RecordThread recordThread;
    private String targetFilePath;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_play_pcm_data;
    }

    @Override
    protected void initListener() {

        File tmpFile = getExternalFilesDir(Environment.DIRECTORY_MUSIC);
//        targetFilePath = tmpFile.getPath() + "/" + "exectorXJJ.pcm";
        targetFilePath = tmpFile.getPath() + "/" + "test_record.pcm";

        recordThread = new PlayPcmDataActivity.RecordThread(new WeakReference<>(this));

    }


    @OnClick({R.id.startRecord, R.id.stopRecord})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.startRecord:
                startPlay();
                break;
            case R.id.stopRecord:
                stopPlay();
                break;
        }
    }

    private void stopPlay() {
        if (null != recordThread) {
            recordThread.stopPlay();
        }
    }

    private void startPlay() {
        if (null != recordThread) {
            recordThread.start();
        }
    }


    static class RecordThread extends Thread {

        //音频管理策略  铃声，系统铃声，警告声，音乐声
        private int streamType = AudioManager.STREAM_MUSIC;
        //采样率
        private int sampleRateInHz  = 44100;
        private int channelConfig   = AudioFormat.CHANNEL_OUT_MONO;
        private int audioFormat     = AudioFormat.ENCODING_PCM_16BIT;
        // int：记录期间写入音频数据的缓冲区的总大小（以字节为单位）。
        // 请参见getMinBufferSize（int，int，int）以确定成功创建AudioRecord实例所需的最小缓冲区大小。
        private int bufferSizeInBytes;

        /**
         * AudioTrack.MODE_STATIC   //需要一次性将所有的数据都写入播放缓冲区，适合播放铃声，较短的音频片段
         * AudioTrack.MODE_STREAM   // 按照一定的时间间隔不间断的写入音频数据。
         */
        private int mode = AudioTrack.MODE_STREAM;


        private WeakReference<PlayPcmDataActivity> weakReference;
        private AudioTrack audioTrack;

        private boolean isExit = false;

        public RecordThread(WeakReference<PlayPcmDataActivity> weakReference) {
            this.weakReference = weakReference;

            bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
            audioTrack = new AudioTrack(streamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, mode);
        }


        @Override
        public void run() {
            super.run();
            if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
                Log.e("RecordThread ", audioTrack.getState() + "");
                return;
            }



            FileInputStream fis = null;
            try {
                fis = new FileInputStream(weakReference.get().targetFilePath);
                byte[] byteBuffer = new byte[bufferSizeInBytes];
                audioTrack.play();

                int size = -1;
                while ((size = fis.read(byteBuffer)) != -1) {
                    Log.e("AudioTrack ", "读取文件的长度   =   " + size);
                    //if (isExit) {
                    //    break;
                    //}
                    checkPlayStatus(audioTrack);
                    audioTrack.write(byteBuffer, 0, size);
                }

                Log.e("AudioTrack ", "读取完成，或者点击了暂停");

//                checkPlayStatus(audioTrack);

                isExit = true;
                audioTrack.stop();
                audioTrack.release();
                audioTrack = null;
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("AudioTrack ", "出现了一个异常");
                if (null != audioTrack) {
                    isExit = true;
                    audioTrack.stop();
                    audioTrack.release();
                    audioTrack = null;
                }
            }
        }

        private void checkPlayStatus(AudioTrack audioTrack) {
            int playStatus = audioTrack.getPlayState();
            switch (playStatus) {
                case 1:
                    Log.e("AudioTrack ", "PLAYSTATE_STOPPED");
                    break;
                case 2:
                    Log.e("AudioTrack ", "PLAYSTATE_PAUSED");
                    break;
                case 3:
                    Log.e("AudioTrack ", "PLAYSTATE_PLAYING");
                    break;
            }
        }

        public void stopPlay() {
            isExit = true;
        }
    }
}
